from rest_framework.decorators import api_view
from rest_framework.response import Response
from movie.models import Behavior,Douban_Movie
from django.db.models.functions import Cast
from django.db.models import FloatField
from surprise.dump import load

from utils.tryRecommand import export_data_to_csv, Recommand_UserCf,Buildmain

from recommand_demo.serializers import MovieSerializer



@api_view(['GET'])
def recommand_movie(request):
    user_id = request.query_params.get('id')
    print('user_id:',user_id)
    if user_id != '':
        # print('user_id：',user_id)
        # 用于构建数据
        recommand = Recommand_UserCf(r'E:\recommend_movie\recommand\utils\data.csv')
        # search_id = Behavior.objects.filter(id=user_id)
        try:
            model = load(r'E:\recommend_movie\recommand\model.plf')
        except Exception as e:
            print('模型不存在,重新生成推荐模型')
            model = Buildmain.delay(r'E:\recommend_movie\recommand\utils\data.csv')
            recommand.save_model(model, r'E:\recommend_movie\recommand\model.plf')
            result = {
                'msg':'正在生成推荐电影中，请重新刷新页面',
                'code':4000
            }
            return Response(result)
        else:
            recommand_list = recommand.tok_k_recommand(str(user_id), 6, 1)
            recommand_movie_id = [movie[0] for movie in recommand_list]
            recommand_list = Douban_Movie.objects.filter(id__in= recommand_movie_id)
            serializer = MovieSerializer(recommand_list,many=True)
            result = {
                'data': serializer.data,
                'code': 2000,
            }
            return Response(result)
    else:
        print('用户没有登录，所以就直接返回评分排名前6的电影')
        top_k = Douban_Movie.objects.annotate(score_float=Cast('score',FloatField())).order_by('-score_float')[:6]
        serializer = MovieSerializer(top_k,many=True)
        result = {
            'data': serializer.data,
            'code': 2000,
        }
        return Response(result)

